package service

import (
	"WebApplication/db"
	"WebApplication/dtos"
	"WebApplication/model"
	"github.com/gin-gonic/gin"
	"github.com/tealeg/xlsx"
	"net/http"
	"strconv"
)


func ExportService(context *gin.Context){
	// 建表 初始化
	file := xlsx.NewFile()
	sheet, err := file.AddSheet("Sheet1")
	if err != nil{
		panic(err)
	}
	row := sheet.AddRow()
	cell := row.AddCell()
	cell.Value = "ID"
	cell = row.AddCell()
	cell.Value = "OrderNo"
	cell = row.AddCell()
	cell.Value = "UserName"
	cell = row.AddCell()
	cell.Value = "Amount"
	cell = row.AddCell()
	cell.Value = "Status"
	cell = row.AddCell()
	cell.Value = "FileUrl"


	DB := context.MustGet("orderdatabase").(*db.OrderDatabase)
	opResult := DB.FindAll()
	// 查询操作失败了 -> 输出失败的响应
	if opResult.Error != nil{
		context.JSON(http.StatusBadRequest, dtos.Response{Successful:false, Message: opResult.Error.Error()})
		return
	}
	// 如果成功  开始导出数据
	order := opResult.Result.([]model.Order)
	for _,v := range order{
		row = sheet.AddRow()
		cell = row.AddCell()
		cell.Value = strconv.Itoa(v.ID)
		cell = row.AddCell()
		cell.Value = v.UserName
		cell = row.AddCell()
		cell.Value = strconv.FormatFloat(v.Amount, 'g', 30, 32)
		cell = row.AddCell()
		cell.Value = v.Status
		cell = row.AddCell()
		cell.Value = v.FileUrl
	}
	file.Save("file.xlsx")
	filename := "file.xlsx"
	filepath := "./"
	context.Header("Content-Type", "application/msexcel")
	context.Header("Content-Disposition", "attachment; filename="+filename)
	context.File(filepath + filename)
}